import React, { PureComponent } from "react";
import { View, StyleSheet, Text, SafeAreaView, BackHandler, DeviceEventEmitter, ToastAndroid } from "react-native";
import { Button, Icon, Overlay } from "react-native-tengits-elements";
import { TText } from "../common/Widgets/WidgetDefault";
import DataCenter from "../logic/DataCenter";
import OverlayBatchBrightness from "./Components/BatchBrightness";
import {OverlayStrategyList} from "./Components/StrategyList";
import { scaleSize } from "../common/Utils/ToolUtils";
import { Colors, FontSize } from "../common/Theme/TTheme";
import ControlSubPage from "./Components/ControlSubPage";
import CommonDrawer from "../common/Widgets/CommonDrawer";
import UICommandExecute from "../logic/UICommandExecute";
import { Adjust_Model } from "../logic/LogicConstant";

export default class LocalCabinetControllPage extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            localCabinet: DataCenter.getLocalCabinetData(),
            strategyList: DataCenter.getStrategyList(),
            batchBrightnessVisible: false,
            strategyListVisible: false,
        };
        this.cacheLight = {};
    }

    componentDidMount() {
        BackHandler.addEventListener("hardwareBackPress", this.onBackAndroid);
        this.localCabinetListener = DeviceEventEmitter.addListener("localCabinet", ()=>{
            this.setState({
                localCabinet: DataCenter.getLocalCabinetData(),
            });
        });
        this.strategyListListener = DeviceEventEmitter.addListener("strategyList", () =>{
            this.setState({
                strategyList: DataCenter.getStrategyList(),
            });
        });
    }

    componentWillUnmount() {
        BackHandler.removeEventListener("hardwareBackPress", this.onBackAndroid);
        this.localCabinetListener.remove();
        this.strategyListListener.remove();
    }

    onBackAndroid = ()=>{
        console.log("on back press")
        return true;
    }

    getHeadTitle = ()=>{
        const{localCabinet} = this.state;
        let baseName = DataCenter.getTunnleBaseInfo();
        return baseName + (localCabinet.gateName ? ("  " +localCabinet.gateName) : "");
    }

    renderHeader() {
        return <View style={styles.header}>
                <Button 
                    buttonStyle={{borderRadius:0, backgroundColor:Colors.button_color, width:scaleSize(117), height:scaleSize(88)}} 
                    icon={<Icon name='menu' color={Colors.white} size={scaleSize(40)}/>}
                    onPress={()=>{
                        this.selectDrawer && this.selectDrawer.showModalAnimate()
                }}/>
                <View style={{flex:1, flexDirection:'row', alignItems:'center', justifyContent:'center'}}>
                    <Text style={{fontSize: FontSize.h3_font, color:Colors.white}}>{`${this.getHeadTitle()}`}</Text>
                    <View style={{alignItems:'center', justifyContent:'center', marginLeft: scaleSize(20), width:scaleSize(100), borderRadius:scaleSize(6), height:scaleSize(40), backgroundColor: Colors.calm_color}}>
                    <Text style={{fontSize: FontSize.h4_font, color:Colors.white}}>
                        {"本柜"}</Text>
                    </View>
                </View>
        </View>
    }

    batchBtnCallback = (data)=>{
        const{localCabinet} = this.state;
        for(let i = 0; i < localCabinet.loop.length; i++) {
            let item = localCabinet.loop[i];
            this.cacheLight[item.loopNumber] = item.loopCurrentValue;
        }
        this.setState({
            batchBrightnessVisible: true,
        });
    }

    strateyBtnCallback = (data)=>{
        const{strategyList} = this.state;
        if(!strategyList || strategyList.length <= 0) {
            ToastAndroid.show("当前无策略配置", ToastAndroid.SHORT);
        } else {
            this.setState({strategyListVisible: true});
        }
    }

    sliderCallback = (data, loopItem, value) =>{
        UICommandExecute.onLocalRealSlider([loopItem.loopNumber], value);
    }

    sliderCompleteCallback = (data, loopItem, value) =>{
        UICommandExecute.onLocalSliderComplete([loopItem.loopNumber], value, true);
    }

    batchSliderCallback = (data, loopNumbers, value) => {
        if(loopNumbers.length > 0) {
            UICommandExecute.onLocalRealSlider(loopNumbers, value);
        }
    }

    batchSliderCompleteCallback = (data, loopNumbers, value) => {
        for(let loop of loopNumbers) {
            this.cacheLight[loop] = value; 
        }
        if(loopNumbers.length > 0) {
            UICommandExecute.onLocalSliderComplete(loopNumbers, value, false);
        }
    }

    toggleOverlay = (key) => {
        const{localCabinet} = this.state;
        if(key == "BatchBrightness") {
            this.setState({batchBrightnessVisible: false});
            for(let i = 0 ; i < localCabinet.loop.length; i++) {
                let oriData = localCabinet.loop[i];
                if(this.cacheLight[oriData.loopNumber] != oriData.loopCurrentValue) {
                    UICommandExecute.onLocalSliderComplete([oriData.loopNumber], oriData.loopCurrentValue, false);
                }
            }
        } else if(key == "StrategySelect") {
            this.setState({strategyListVisible: false});
        }
    }

    onSure = (key, params) => {
        if(key == "BatchBrightness") {
            console.log("params:",params);
            if(params.model == Adjust_Model.ADJUST_DIRECT_LIGHT) {
                UICommandExecute.onLocalSliderComplete(params.loops, params.light, true);
            } else {
                UICommandExecute.onLocalStrategySelect(params.loops, params.strategy.id);
            }
            this.setState({batchBrightnessVisible: false});
        } else if(key == "StrategySelect") {
            this.setState({strategyListVisible: false});
        }
    }

    renderMenuDrawer() {
        const{navigation} = this.props;
        return <View style={{flex:1, flexDirection:'column', justifyContent:'space-between', paddingHorizontal:scaleSize(44)}}>
                <Button buttonStyle={{height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"本控制柜管控"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"集群控制柜管控"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('Colony')
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}}
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"单洞分段调控"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('SingleHole')
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"控制柜运行概览"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('DeviceSummary')
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}}
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"设备信息"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('DeviceInfo')
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}}
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"注册管理"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('RegisterDevice')
                }}/>
            </View>
    }

    render() {
        const{localCabinet, strategyList, batchBrightnessVisible, strategyListVisible} = this.state;
        return <SafeAreaView style={styles.container}>
                {this.renderHeader()}
                <ControlSubPage data={localCabinet}
                batchBtnCallback={this.batchBtnCallback} 
                strateyBtnCallback={this.strateyBtnCallback}
                sliderCallback={this.sliderCallback}
                sliderCompleteCallback={this.sliderCompleteCallback}
                />
                <CommonDrawer ref={(r) => {
                        this.selectDrawer = r;
                    }} contentView={this.renderMenuDrawer()}/>
                <Overlay overlayStyle={{padding:0}} isVisible={batchBrightnessVisible} onBackdropPress={()=>{this.toggleOverlay("BatchBrightness")}} fullScreen>
                    <OverlayBatchBrightness data={localCabinet}
                    sliderCallback={this.batchSliderCallback}
                    sliderCompleteCallback={this.batchSliderCompleteCallback}
                    toggleOverlay={this.toggleOverlay}
                    strategyList={strategyList}
                    onSure={this.onSure}/>
                </Overlay>
                <Overlay overlayStyle={{padding:0}} isVisible={strategyListVisible} onBackdropPress={()=>{this.toggleOverlay("StrategySelect")}} fullScreen>
                    <OverlayStrategyList data={strategyList} canSel={false}  toggleOverlay={this.toggleOverlay}
                        id={strategyList[0]?.id}
                    />
                </Overlay>
            </SafeAreaView>
    }
}

const styles = StyleSheet.create({
    container:{
        flex:1, 
        backgroundColor: Colors.page_bg_color, 
        justifyContent:'space-around'
    },
    header:{
        flexDirection: 'row',
        height: scaleSize(88),
        backgroundColor: Colors.navibar_color,
    },
});